<template>
  <div class="app-container">
    <el-form :model="queryParams"
             ref="queryForm"
             v-show="showSearch"
             :inline="true">
      <el-form-item label="策略名称"
                    prop="name">
        <el-input v-model="queryParams.name"
                  placeholder="请输入策略名称"
                  clearable
                  size="small"
                  style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="mini"
                   @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"
                   size="mini"
                   @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10"
            class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleSave"
                   v-hasPermi="['trade:strategy:save']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   plain
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-hasPermi="['trade:strategy:update']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleRemove"
                   v-hasPermi="['trade:strategy:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch"
                     @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="strategyList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"
                       align="center" />
      <el-table-column label="编号"
                       prop="id"
                       align="center" />
      <el-table-column label="策略名称"
                       prop="name"
                       :show-overflow-tooltip="true"
                       align="center" />
      <el-table-column label="创建时间"
                       prop="createdTime"
                       align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间"
                       prop="createdTime"
                       align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['trade:strategy:update']">修改</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleRemove(scope.row)"
                     v-hasPermi="['trade:strategy:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList" />
    <!-- 添加或编辑 -->
    <el-dialog :title="title"
               :visible.sync="open"
               :destroy-on-close="true"
               width="1000px">
      <div>
        <div class="flex et">
          <p>策略名称:</p>
          <el-input placeholder="请输入策略内容"
                    v-model="row.name"
                    clearable>
          </el-input>
        </div>
        <div class="e-wrap">
          <p class="e-title">买入条件</p>
          <div class="e-list">
            <div class="flex e-i"
                 v-for="(condition,i) in row.buyConditions"
                 :key="i">
              <div>
                <span>左侧特征</span>
                <el-select v-model="condition.leftFeature.id"
                           placeholder="请选择特征">
                  <el-option v-for="item in featureOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div>
                <span>运算符</span>
                <el-select v-model="condition.operator.id"
                           placeholder="请选择运算符">
                  <el-option v-for="item in operatorOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div>
                <span>右侧特征</span>
                <el-select v-model="condition.rightFeature.id"
                           placeholder="请选择特征">
                  <el-option v-for="item in featureOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="e-action">
                <i class="el-icon-plus"
                   @click="addChildRow('buy')"></i>
                <i class="el-icon-minus"
                   @click="subChildRow('buy',condition,i)"></i>
              </div>
            </div>
          </div>
        </div>
        <!-- 卖出条件 -->
        <div class="e-wrap">
          <p class="e-title">卖出条件</p>
          <div class="e-list">
            <div class="flex e-i"
                 v-for="(condition,i) in row.sellConditions"
                 :key="i">
              <div>
                <span>左侧特征</span>
                <el-select v-model="condition.leftFeature.id"
                           placeholder="请选择特征">
                  <el-option v-for="item in featureOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div>
                <span>运算符</span>
                <el-select v-model="condition.operator.id"
                           placeholder="请选择运算符">
                  <el-option v-for="item in operatorOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div>
                <span>右侧特征</span>
                <el-select v-model="condition.rightFeature.id"
                           placeholder="请选择特征">
                  <el-option v-for="item in featureOptions"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="e-action">
                <i class="el-icon-plus"
                   @click="addChildRow('sell')"></i>
                <i class="el-icon-minus"
                   @click="subChildRow('sell',d,i)"></i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveStrategy,
  removeStrategy,
  updateStrategy,
  getStrategy,
  searchStrategy,
} from '@/api/trade/strategy'
import { createLogger } from 'vuex'

export default {
  name: 'Strategy',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 特征表格数据
      strategyList: [],
      // 特征选项
      featureOptions: [],
      // 运算符选项
      operatorOptions: [],
      // 操作类型
      operationType: undefined,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: undefined,
      },
      row: {
        id: undefined,
        name: undefined,
        buyConditions: [{ leftFeature: {}, operator: {}, rightFeature: {} }],
        sellConditions: [{ leftFeature: {}, operator: {}, rightFeature: {} }],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询特征列表 */
    getList() {
      this.loading = true
      searchStrategy(this.queryParams).then((response) => {
        this.strategyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.row = {
        name: undefined,
        buyConditions: [{ leftFeature: {}, operator: {}, rightFeature: {} }],
        sellConditions: [{ leftFeature: {}, operator: {}, rightFeature: {} }],
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleSave() {
      this.reset()
      this.operationType = 'add'
      getStrategy().then((response) => {
        this.featureOptions = response.features
        this.operatorOptions = response.operators
        this.open = true
        this.title = '添加策略'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.operationType = 'update'
      this.row.id = row.id
      const id = row.id || this.ids
      getStrategy(id).then((response) => {
        this.row = response.data
        this.featureOptions = response.features
        this.operatorOptions = response.operators
        this.open = true
        this.title = '修改策略'
      })
    },
    /** 删除按钮操作 */
    handleRemove(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除特征编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return removeStrategy(ids)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    // 新增条件
    addChildRow(type) {
      if (type == 'buy') {
        this.row.buyConditions.push({
          leftFeature: {},
          operator: {},
          rightFeature: {},
        })
      } else {
        this.row.sellConditions.push({
          leftFeature: {},
          operator: {},
          rightFeature: {},
        })
      }
    },
    // 删除条件
    subChildRow(type, d, i) {
      if (type == 'buy') {
        if (this.row.buyConditions.length <= 1) return
        this.row.buyConditions.splice(i, 1)
      } else {
        if (this.row.sellConditions.length <= 1) return
        this.row.sellConditions.splice(i, 1)
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      let data = {
        buyConditions: [],
        sellConditions: [],
        name: undefined,
        id: undefined,
      }
      let name = this.row.name
      data.name = name
      if (!name) {
        this.msgError('策略名称不能为空')
        return
      }
      let buyConditions = this.row.buyConditions
      let sellConditions = this.row.sellConditions
      for (let i2 in buyConditions) {
        if (!buyConditions[i2].leftFeature.id) {
          this.msgError('买入条件左侧特征不能为空')
          return
        }
        if (!buyConditions[i2].operator.id) {
          this.msgError('买入条件运算符不能为空')
          return
        }
        if (!buyConditions[i2].rightFeature.id) {
          this.msgError('买入条件右侧特征不能为空')
          return
        }
        data['buyConditions'].push({
          leftFeatureId: buyConditions[i2].leftFeature.id,
          operatorId: buyConditions[i2].operator.id,
          rightFeatureId: buyConditions[i2].rightFeature.id,
        })
      }
      for (let i2 in sellConditions) {
        if (!sellConditions[i2].leftFeature.id) {
          this.msgError('买入条件右侧特征不能为空')
          return
        }
        if (!sellConditions[i2].operator.id) {
          this.msgError('买入条件运算符不能为空')
          return
        }
        if (!sellConditions[i2].rightFeature.id) {
          this.msgError('买入条件右侧特征不能为空')
          return
        }
        data['sellConditions'].push({
          leftFeatureId: sellConditions[i2].leftFeature.id,
          operatorId: sellConditions[i2].operator.id,
          rightFeatureId: sellConditions[i2].rightFeature.id,
        })
      }
      if (this.operationType == 'add') {
        saveStrategy(data).then((response) => {
          this.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      } else {
        data.id = this.row.id
        updateStrategy(data).then((response) => {
          this.msgSuccess('修改成功')
          this.open = false
          this.getList()
        })
      }
    },
  },
}
</script>

<style scoped>
.et {
  white-space: nowrap;
}
.et p {
  margin-right: 10px;
}
.e-action i {
  width: 23px;
  height: 23px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f1f1f1;
  border-radius: 5px;
  font-size: 10px;
  font-weight: bold;
  margin: 0 10px;
  color: #888888;
}
.e-wrap {
  border: 1px solid #e1e1e1;
  border-radius: 10px;
  margin: 20px auto;
  padding: 5px 10px;
}
.flex {
  display: flex;
  align-items: center;
}
.e-title {
  line-height: 0px;
  text-align: center;
  font-weight: bold;
}
.e-i > div {
  margin: 5px 0;
  display: flex;
  align-items: center;
  font-size: 13px;
  white-space: nowrap;
  margin-right: 15px;
}
.e-i > div > span {
  margin: 0 10px;
  color: #888888;
}
</style>